# -*- coding:utf-8 -*-
# @Author : mistchan
# @Time : 2021/5/14 0014 23:21
# @File : main.py
# @Software: PyCharm
import json
import glob
from datetime import datetime
from datetime import timedelta
import poplib
import os
from email.parser import Parser
from email.header import decode_header
# from email.utils import parseaddr
import email
from PyPDF2 import PdfFileReader, PdfFileWriter, PdfFileMerger
from merge_pdfs import merge_to_one

def merge_pdfs(pdf_file_dirt):
    file_writer = PdfFileWriter()
    for each in glob.glob(f'.\\{pdf_file_dirt}\\*.pdf'):
        # 循环读取需要合并pdf文件
        file_reader = PdfFileReader(each)
        # 遍历每个pdf的每一页
        for page in range(file_reader.getNumPages()):
            # 写入实例化对象中
            file_writer.addPage(file_reader.getPage(page))

    with open(f'.\\{pdf_file_dirt}\\pdf_merged.pdf', 'wb') as out:
        file_writer.write(out)


with open('pwd.json', 'r', encoding='utf-8') as f:
    pwd_info = json.load(f)


def guess_charset(msg):
    charset = msg.get_charset()
    if charset is None:
        content_type = msg.get('Content-Type', '').lower()
        pos = content_type.find('charset=')
        if pos >= 0:
            charset = content_type[pos + 8:].strip()
    return charset


def get_content(msg):
    content = ''
    content_type = msg.get_content_type()
    # print('content_type:',content_type)
    if content_type == 'text/plain':  # or content_type == 'text/html'
        content = msg.get_payload(decode=True)
        charset = guess_charset(msg)
        if charset:
            content = content.decode(charset)
    return content


def decode_str(str_in):
    value, charset = decode_header(str_in)[0]
    if charset:
        value = value.decode(charset)
    return value


def get_att(msg_in, dirt_name):
    attachment_files = []
    name_prefix = datetime.utcnow().strftime('%M%S%f')
    for part in msg_in.walk():
        # 获取附件名称类型
        file_name = part.get_param("name")  # 如果是附件，这里就会取出附件的文件名
        # file_name = part.get_filename() #获取file_name的第2中方法
        # contType = part.get_content_type()
        
        if file_name:
            h = email.header.Header(file_name)
            # 对附件名称进行解码
            dh = email.header.decode_header(h)
            filename = dh[0][0]
            if filename:
                # 将附件名称可读化
                filename = f"{name_prefix}_{decode_str(str(filename, dh[0][1]))}"
                # filename = filename.encode("utf-8")
            # 下载附件
            data = part.get_payload(decode=True)
            # 在指定目录下创建文件，注意二进制文件需要用wb模式打开
            if not os.path.exists(dirt_name):
                os.mkdir(dirt_name)
            att_file = open(f'{dirt_name}\\{filename}', 'wb')
            att_file.write(data)  # 保存附件
            att_file.close()
            attachment_files.append(filename)
        # else:
        #     # 不是附件，是文本内容
        #     # print(get_content(part))
        #     # # 如果ture的话内容是没用的
        #     # if not part.is_multipart():
        #     #     # 解码出文本内容，直接输出来就可以了。
        #     #     print(part.get_payload(decode=True).decode('utf-8'))
        #     pass
    return attachment_files


def get_email_content(dir_to_save):
    useraccount = pwd_info['user_qq']
    password = pwd_info['imap_qq']

    # 邮件服务器地址,以下为网易邮箱
    # pop3_server = 'pop.163.com'
    pop3_server = 'pop.qq.com'

    # 开始连接到服务器
    server = poplib.POP3(pop3_server)

    # 打开或者关闭调试信息，为打开，会在控制台打印客户端与服务器的交互信息
    server.set_debuglevel(0)

    # 打印POP3服务器的欢迎文字，验证是否正确连接到了邮件服务器
    # print(server.getwelcome().decode('utf8'))

    # 开始进行身份验证
    server.user(useraccount)
    server.pass_(password)

    # 返回邮件总数目和占用服务器的空间大小（字节数）， 通过stat()方法即可
    email_num, email_size = server.stat()
    # print("消息的数量: {0}, 消息的总大小: {1}".format(email_num, email_size))

    # 使用list()返回所有邮件的编号，默认为字节类型的串
    rsp, msg_list, rsp_siz = server.list()
    # print("服务器的响应: {0},\n消息列表： {1},\n返回消息的大小： {2}".format(rsp, msg_list, rsp_siz))

    # 下面单纯获取最新的一封邮件
    total_mail_numbers = len(msg_list)
    dirt_name = dir_to_save
    for i in range(1, total_mail_numbers+1):
        rsp, msglines, msgsiz = server.retr(i)
        # print("服务器的响应: {0},\n原始邮件内容： {1},\n该封邮件所占字节大小： {2}".format(rsp, msglines, msgsiz))

        msg_content = b'\r\n'.join(msglines).decode('utf-8')

        msg = Parser().parsestr(text=msg_content)

        now = datetime.now()
        date_from = datetime.strptime(msg.get("Date")[:24], '%a, %d %b %Y %H:%M:%S')
        time_delta = now - date_from
        one_day = timedelta(days=1)

        # if 'didifapiao@mailgate.xiaojukeji.com' in msg.get('from') and time_delta < one_day:
        if time_delta <= one_day:
        
            get_att(msg, dirt_name)



        # 关闭与服务器的连接，释放资源
    # rsp, msglines, msgsiz = server.retr(total_mail_numbers-6)
    # # print("服务器的响应: {0},\n原始邮件内容： {1},\n该封邮件所占字节大小： {2}".format(rsp, msglines, msgsiz))
    #
    # msg_content = b'\r\n'.join(msglines).decode('gbk')
    #
    # msg = Parser().parsestr(text=msg_content)
    # print(msg.get('Received'))
    server.close()
    return len(msg_list)


if __name__ == '__main__':
    get_email_content('.\\手动放入需要合并的文件')
    